<template>
  <div class="advert-campaign-wrap table-gl-w">
    <a-tabs v-model:active-key="activeTab" @change="changeActiveTab" size="mini">
      <a-tab-pane :key="0" title="待处理" />
      <a-tab-pane :key="1" title="观察期" />
    </a-tabs>
    <div class="search-w table-filter-form">
      <div class="filter-list flex-c">
        <template v-for="(item, i) in filterItem" :key="i">
          <div class="filter-item">
            <template v-if="item.key == 'portfolioIds'">
              <portfolioIdsMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.key == 'campaignIds'">
              <CampaignIdsMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select_multiple'">
              <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" :resultTags="resultTags" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select'">
              <a-select v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear @change="setSearchVal">
                <a-option v-for="(option, s) in item.optionItems" :key="s" :value="option.value" :label="option.label" />
              </a-select>
            </template>
            <template v-else-if="item.type == 'keyword_date_range'">
              <filterDateRange :data="item" @search="setSearchVal" />
            </template>
          </div>
        </template>
        <!-- 气泡 -->
        <a-popover trigger="click" ref="selectMulRef" position="bottom" @popup-visible-change="popupVisibleChange">
          <template #content>
            <ul class="target-filter-w">
              <li class="flex-c" v-for="item in filterItemSub" :key="item.key">
                <span class="label">{{ item.label }}：</span>
                <template v-if="item.type == 'select_multiple'">
                  <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" :resultTags="resultTags" @change="selectMulVal($event, item, false)" />
                </template>
                <template v-else-if="item.type == 'select'">
                  <a-select v-model="item.value" :placeholder="item.placeholder || item.label" allow-clear>
                    <a-option v-for="(option, s) in item.optionItems" :key="s" :value="option.value" :label="option.label" />
                  </a-select>
                </template>
              </li>
              <li class="flex-c" v-for="(item, i) in extendMetricsSearches" :key="i">
                <span class="label">{{ AdTargetKeys[item.field] }}：</span>
                <a-input-number v-model="item.minValue" style="width: 120px" placeholder="请输入" size="small">
                  <template #suffix>
                    <span class="unit">{{ item.unit }}</span>
                  </template>
                </a-input-number>
                <span class="line">—</span>
                <a-input-number v-model="item.maxValue" style="width: 120px" placeholder="请输入" size="small">
                  <template #suffix>
                    <span class="unit">{{ item.unit }}</span>
                  </template>
                </a-input-number>
              </li>
            </ul>
            <div class="flex-c-end" style="margin-top: 20px">
              <a-space>
                <a-button size="mini" @click="closePopover">取消</a-button>
                <a-button type="primary" size="mini" @click="setTargetFilter">确认</a-button>
              </a-space>
            </div>
          </template>
          <a-button class="gray-outline filter-item">
            <template #icon>
              <icon-filter />
            </template>
          </a-button>
        </a-popover>
        <div class="filter-item">
          <a-button @click="resetAll">重置</a-button>
        </div>
      </div>
    </div>
    <!-- 图表 -->
    <RiskAdChart ref="adChartRef" :searchParams="searchParam" />
    <!-- table列表 -->
    <RiskAdvertAwaitTable :type="activeTab" ref="riskAdvertAwaitTableRef" :markedtList="markedtList" :userList="userList" :shopList="shopList" :searchParams="searchParam" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'CampaignManagement',
  })
</script>
<script lang="ts" setup>
  import { ref, onMounted, nextTick, defineComponent } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import { getShopMarketAll, getOrganizesUser } from '@/api/system'
  import selectMultiple from '@/components/Form/selectMultiple.vue'
  import portfolioIdsMultiple from './components/portfolioIdsMultiple.vue'
  import filterDateRange from '@/components/Form/filterDateRange.vue'
  import RiskAdvertAwaitTable from './components/riskAdvertAwaitTable.vue'
  import RiskAdChart from './components/riskAdChart.vue'
  import CampaignIdsMultiple from './components/campaignIdsMultiple.vue'
  import { AdTargetKeys } from '../types'

  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(() => {
    getMarketList()
    getShopList()
    getUserList()
    changeActiveTab(0)
  })

  // 指标范围过滤
  const extendMetricsSearches = ref<Array<any>>([{ field: 'impressions' }, { field: 'clicks' }, { field: 'ctr', unit: '%' }, { field: 'cost' }, { field: 'cpc' }, { field: 'purchasesOrder' }, { field: 'saleAmount' }, { field: 'cvr', unit: '%' }, { field: 'cpa' }, { field: 'acos', unit: '%' }, { field: 'roas' }])
  const activeTab = ref(0)
  const userList = ref([])
  const markedtList = ref([])
  const shopList = ref<Array<any>>([])
  const resultTags = ref<any>([])
  const selectMulRef = ref()
  const searchParam = ref<any>({})
  const riskAdvertAwaitTableRef = ref()
  const adChartRef = ref()
  const metricsSearchesReault = ref<Array<any>>([])
  const useBaseData = useBaseDataStore()
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIds',
      label: '站点',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopIds',
      label: '全部店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'portfolioIds',
      label: '广告组合',
      value: ref(),
      type: 'portfolioIds',
      width: 120,
      optionItems: [],
    },
    {
      key: 'campaignIds',
      label: '广告活动',
      value: ref(),
      type: 'campaignIds',
      width: 120,
      optionItems: [],
    },
    {
      key: 'operationsIds',
      label: '销售员',
      value: ref(),
      type: 'select_multiple',
      width: 100,
      optionItems: [],
    },
    {
      type: 'keyword_date_range',
      key: 'date',
      keyItems: [{ label: '开始日期', value: 'date' }],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '开始日期',
      width: 240,
    },
    {
      type: 'keyword_date_range',
      key: 'handleDate',
      keyItems: [{ label: '最近操作时间', value: 'handleDate' }],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '最近操作时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const filterItemSub = ref<Array<FilterTableItem>>([
    {
      key: 'adTypes',
      label: '广告类型',
      value: ref(),
      type: 'select_multiple',
      width: 100,
      optionItems: [
        {
          label: '商品广告',
          value: 'SPONSORED_PRODUCTS',
        },
        {
          label: '品牌广告',
          value: 'SPONSORED_BRANDS',
        },
        {
          label: '展示广告',
          value: 'SPONSORED_DISPLAY',
        },
      ],
    },
    {
      key: 'targetingType',
      label: '投放类型',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        {
          label: '关键词投放',
          value: '关键词投放',
        },
        {
          label: '商品投放',
          value: '商品投放',
        },
        {
          label: '内容相关投放',
          value: '内容相关投放',
        },
        {
          label: '受众',
          value: '受众',
        },
        {
          label: '自动投放',
          value: '自动投放',
        },
      ],
    },
  ])

  // 获取站点
  async function getMarketList() {
    const res: any = await getShopMarketAll()
    markedtList.value = res?.data || []
    filterItem.value[0].optionItems = res?.data?.map((el: any) => {
      return {
        label: el.marketplaceName,
        value: el.marketplaceId,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    shopList.value = useBaseData.shopList
    filterItem.value[1].optionItems = useBaseData.shopList?.map((el: any) => {
      return {
        label: el.shopName,
        value: el.id,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    const res: any = await getOrganizesUser({
      pageNum: 1,
      pageSize: 1000,
    })
    userList.value = res?.data?.records || []
    filterItem.value[4].optionItems = userList.value?.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 切换tabs
  function changeActiveTab(tab: number) {
    activeTab.value = tab
    setSearchVal()
  }

  // 批量选择数据
  function selectMulVal(searchVal: any, item: any, notAllow = true) {
    item.value = searchVal
    if (notAllow) {
      setSearchVal()
    }
  }
  function setSearchVal() {
    searchParam.value = {}
    filterItem.value.forEach((el: FilterTableItem) => {
      if (el.key == 'date') {
        searchParam.value.startDate = el.value?.[0]
        searchParam.value.endDate = el.value?.[1]
      } else if (el.key == 'handleDate') {
        searchParam.value.lastUpdateDateTimeStart = el.value?.[0]
        searchParam.value.lastUpdateDateTimeEnd = el.value?.[1]
      } else if (el.key === 'portfolioIds' && el.value instanceof Array) {
        searchParam.value.portfolioIds = el.value.map((el: any) => el.portfolioId)
      } else if (el.key === 'campaignIds' && el.value instanceof Array) {
        searchParam.value.campaignIds = el.value.map((el: any) => el.campaignId)
      } else {
        searchParam.value[el.key] = el.value
      }
    })
    filterItemSub.value.forEach((el: FilterTableItem) => {
      searchParam.value[el.key] = el.value
    })
    if (metricsSearchesReault.value.length) {
      searchParam.value['extendMetricsSearches'] = metricsSearchesReault.value
    }
    startSearch()
  }
  function startSearch() {
    nextTick(() => {
      riskAdvertAwaitTableRef.value.getTableListByVal()
      adChartRef.value.refreshData()
    })
  }
  function resetAll() {
    filterItem.value.forEach((el: FilterTableItem) => {
      el.value = ref()
    })
    metricsSearchesReault.value = []
    setSearchVal()
  }

  // 获取其他指标的查询参数
  function setTargetFilter() {
    metricsSearchesReault.value = extendMetricsSearches.value.filter((el: any) => el.maxValue || el.maxValue === 0 || el.minValue || el.minValue === 0)
    setSearchVal()
    closePopover()
  }
  function closePopover() {
    selectMulRef.value.handlePopupVisibleChange(false)
  }
  function popupVisibleChange(status: boolean) {
    if (status) {
      extendMetricsSearches.value.forEach((el: any) => {
        let currentItem = metricsSearchesReault.value.find((item: any) => item.field == el.field)
        el.minValue = currentItem?.minValue
        el.maxValue = currentItem?.maxValue
      })
      filterItemSub.value.forEach((el: FilterTableItem) => {
        el.value = searchParam.value[el.key]
      })
    }
  }
</script>
<style lang="less" scoped>
  .arco-tabs {
    background-color: #fff;
  }
  .filter-item {
    margin-right: 8px;
    margin-bottom: 5px;
  }
  .filter-result {
    margin-bottom: 5px;
  }
  .filter-list {
    flex-wrap: wrap;
  }
  .target-filter-w {
    li {
      margin-bottom: 10px;
    }
    .label {
      font-size: 12px;
      color: #888;
      width: 90px;
      text-align: right;
      flex-shrink: 0;
    }
    .unit {
      font-size: 12px;
    }
    .line {
      margin: 0 8px;
      color: #999;
    }
    :deep(.arco-input-suffix) {
      padding: 0;
    }
  }
  .arco-scrollbar {
    flex: 1;
    overflow-y: hidden;
    margin-top: 5px;
  }
  .error-w {
    flex: 1;
    background-color: #fff;
    margin-top: 10px;
  }
</style>
